#!/usr/bin/python
#coding: utf-8
import SocketServer
import time

class MyServer(SocketServer.BaseRequestHandler):
	def recvfile(self,filename):
		print 'starting reve file!'
		f = open('./upfile/'+filename,'wb')
		self.request.send('read')
		while True:
			data = self.request.recv(4096)
			if data  == 'EOF':
				print 'recv file success!'
				break
			f.write(data)
		f.close()

	def sendfile(self,filename):
		print 'starting send file!'
		self.request.send('read')
		time.sleep(1)
		f = open('./downfile/'+filename,'rb')
		while True:
			data = f.read(4096)
			if not data:
				break
			self.request.send(data)
		f.close()
		time.sleep(1)
		self.request.send('EOF')
		print 'send file success!'

	def handle(self):
		print 'get connection from :',self.client_address
		while True:
			try:
				data = self.request.recv(4096)
				print 'get data:',data
				if not data:
					print 'break the connection'
					break
				else:
					action,filename = data.split()
					if action == 'put':
						self.recvfile(filename)
					elif action == 'get':
						self.sendfile(filename)
					else:
						print 'get error!'
						continue
			except Exception,e:
				print 'get error at:',e

if __name__ == '__main__':
	host = '127.0.0.1'
	port = 60000
	s = SocketServer.ThreadingTCPServer((host,port),MyServer)
	s.serve_forever()


